defmodule EliPhxPlayWeb.ChatLive do
  use EliPhxPlayWeb, :live_view

  def mount(_params, _session, socket) do
    # 订阅聊天频道
    if connected?(socket) do
      Phoenix.PubSub.subscribe(EliPhxPlay.PubSub, "chat")
    end

    {:ok, assign(socket,
      messages: [],
      username: "用户#{:rand.uniform(1000)}",
      message: ""
    )}
  end

  def render(assigns) do
    ~H"""
    <div class="max-w-2xl mx-auto mt-6">
      <div class="bg-white rounded-lg shadow-lg overflow-hidden">
        <!-- 聊天标题 -->
        <div class="bg-blue-500 text-white p-4">
          <h1 class="text-xl font-bold">💬 实时聊天室</h1>
          <p class="text-sm opacity-90">当前用户: <%= @username %></p>
        </div>

        <!-- 消息区域 -->
        <div class="h-64 overflow-y-auto p-4 bg-gray-50" id="messages">
          <%= if @messages == [] do %>
            <p class="text-gray-500 text-center">还没有消息，开始聊天吧！</p>
          <% else %>
            <%= for msg <- @messages do %>
              <div class={"mb-3 p-2 rounded #{if msg.username == @username, do: "bg-blue-100 ml-8", else: "bg-white mr-8"}"}>
                <div class="flex justify-between items-start">
                  <strong class="text-sm text-gray-600"><%= msg.username %></strong>
                  <span class="text-xs text-gray-400"><%= msg.time %></span>
                </div>
                <p class="mt-1"><%= msg.content %></p>
              </div>
            <% end %>
          <% end %>
        </div>

        <!-- 输入区域 -->
        <form phx-submit="send_message" class="p-4 border-t">
          <div class="flex space-x-2">
            <input
              type="text"
              name="message"
              value={@message}
              phx-change="update_message"
              placeholder="输入消息..."
              class="flex-1 p-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
              autocomplete="off"
            />
            <button
              type="submit"
              class="bg-blue-500 hover:bg-blue-700 text-white px-4 py-2 rounded-lg transition-colors"
            >
              发送
            </button>
          </div>
        </form>
      </div>
    </div>
    """
  end

  # 更新输入框内容
  def handle_event("update_message", %{"message" => message}, socket) do
    {:noreply, assign(socket, message: message)}
  end

  # 发送消息
  def handle_event("send_message", %{"message" => message}, socket) do
    if String.trim(message) != "" do
      # 广播消息给所有用户
      Phoenix.PubSub.broadcast(EliPhxPlay.PubSub, "chat", {
        :new_message,
        %{
          username: socket.assigns.username,
          content: String.trim(message),
          time: DateTime.utc_now() |> DateTime.to_time() |> Time.to_string() |> String.slice(0, 5)
        }
      })
    end

    {:noreply, assign(socket, message: "")}
  end

  # 接收广播的消息
  def handle_info({:new_message, msg}, socket) do
    messages = socket.assigns.messages ++ [msg]
    # 只保留最新的20条消息
    messages = Enum.take(messages, -20)

    {:noreply, assign(socket, messages: messages)}
  end
end
